/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.oplevka.lahvodroid;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Ondra
 */
public class AddActivity extends Activity {
    
    private static final int MENU_ITEM_1 = Menu.FIRST + 1;
    private static final int MENU_ITEM_2 = Menu.FIRST + 2;
    private static final int MENU_ITEM_3 = Menu.FIRST + 3;
    private static XMLBeerList xmlBeerList;
                
    Toast msg;
    
    Button buttonSave;
    ImageButton buttonCamera;
    EditText textEditJmeno;
    EditText textEditPivovar;
    EditText textEditPoznamka;
    EditText textEditAlkohol;
    EditText textEditBarcode;
    Spinner spinnerTyp;
    
    String textJmeno;
    String textPivovar;
    String textAlkohol ;
    String textPoznamka;
    String textTyp;
    String textBarcode;
    
    String SD_CARD_PATH;
    File file;
    
    

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_relative);
        Spinner s = (Spinner) findViewById(R.id.widget133);
        xmlBeerList = XMLHandler.getXMLBeerList();
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
            this, R.array.beerType, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(adapter);
        
        String barcode = FirstActivity.getContents();
        
        if(barcode!=null){
            textEditBarcode = (EditText)findViewById(R.id.widget153);
            textEditBarcode.setText(barcode, EditText.BufferType.EDITABLE);
        }
        buttonCamera = (ImageButton) findViewById(R.id.widget131);
        buttonCamera.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		      //  intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
		        startActivityForResult(intent, 0);
            }
        });
        
        
        buttonSave = (Button) findViewById(R.id.widget137);
         buttonSave.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 saveButton();
                 
                 
                                 
             }

            
         });
    }   
    
     @Override
     public boolean onCreateOptionsMenu(Menu menu)
     {
        menu.add(Menu.NONE, MENU_ITEM_1, Menu.NONE,
            "Add").setIcon(R.drawable.ic_menu_add);

        menu.add(Menu.NONE, MENU_ITEM_2, Menu.NONE,
        "Export").setIcon(R.drawable.ic_menu_save);

        menu.add(Menu.NONE, MENU_ITEM_3, Menu.NONE,
        "Close").setIcon(R.drawable.ic_menu_close_clear_cancel);

        return (super.onCreateOptionsMenu(menu));

       }

        @Override
        public boolean onOptionsItemSelected(MenuItem item)
        {
        switch (item.getItemId()){
        case MENU_ITEM_1:
            msg = Toast.makeText(AddActivity.this,
                    "Menu Item 1 Clicked", Toast.LENGTH_LONG);
            msg.show();
        break;

        case MENU_ITEM_2:
        msg = Toast.makeText(AddActivity.this,
                "Exporting...", Toast.LENGTH_LONG);
        msg.show();
        break;


        case MENU_ITEM_3:
            finish();                
        }
    return (super.onOptionsItemSelected(item));
    }
        
    private void saveButton() {        
        SD_CARD_PATH = Environment.getExternalStorageDirectory().toString();
        file = new File(SD_CARD_PATH + "/Lahvodroid/test.xml");
        
        textEditJmeno    = (EditText)findViewById(R.id.widget65);
        textEditPivovar  = (EditText)findViewById(R.id.widget136);
        textEditAlkohol  = (EditText)findViewById(R.id.widget69);
        textEditPoznamka = (EditText)findViewById(R.id.widget81);
        spinnerTyp       = (Spinner)findViewById(R.id.widget133);
        textEditBarcode  = (EditText)findViewById(R.id.widget153);
        
        textJmeno    = textEditJmeno.getText().toString();
        textPivovar  = textEditPivovar.getText().toString();
        textAlkohol  = textEditAlkohol.getText().toString();
        textPoznamka = textEditPoznamka.getText().toString();
        textTyp      = spinnerTyp.getSelectedItem().toString();
        textBarcode  = textEditBarcode.getText().toString();
                
        
        if (xmlBeerList.getMap().containsKey(textBarcode)){
            msg = Toast.makeText(AddActivity.this,
                    "Nelze uložit! Již existuje záznam s "
                    + "tímto čárovým kódem!", Toast.LENGTH_LONG);
                msg.show();
        } else {
            saveButtonBefore();
        }
                
        
    }
      
    private void saveButtonBefore() {    
        String itemStart    = "    <item>";
        String xmlJmenoTyp  = "        <jmeno typ=\""+textTyp+"\">"+textJmeno+"</jmeno>";
        String xmlPivovar   = "        <pivovar>"+textPivovar+"</pivovar>";
        String xmlAlkohol   = "        <alkohol>"+textAlkohol+"</alkohol>";
        String xmlPoznamka  = "        <poznamka>"+textPoznamka+"</poznamka>";
        String xmlBarcode   = "        <barcode>"+textBarcode+"</barcode>";
        String itemEnd      = "    </item>";
        String maintagEnd   = "</maintag>";
        String nL           = "\n"; 
        
        String toWrite = nL +itemStart + nL + xmlJmenoTyp + nL + xmlPivovar + nL 
                + xmlAlkohol + nL + xmlPoznamka + nL + xmlBarcode + nL 
                + itemEnd + nL + maintagEnd;
        
        FileInputStream fs = null;
        InputStreamReader in = null;
        BufferedReader br = null;

        StringBuilder sb = new StringBuilder();

        String textinLine;

        try {
             fs = new FileInputStream(file);
             in = new InputStreamReader(fs);
             br = new BufferedReader(in);

            while(true)
            {
                textinLine=br.readLine();
                if(textinLine==null)
                    break;
                sb.append(textinLine);
            }
              String textToEdit1 = "</maintag>";
              int cnt1 = sb.indexOf(textToEdit1);
              sb.replace(cnt1,cnt1+textToEdit1.length(),toWrite);

//              String textToEdit2 = "</area>";
//              int cnt2 = sb.indexOf(textToEdit2);
//              sb.replace(cnt2,cnt2+textToEdit2.length(),"Second new edit text");

              fs.close();
              in.close();
              br.close();

            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }

            try{
                FileWriter fstream = new FileWriter(file);
                BufferedWriter outobj = new BufferedWriter(fstream);
                outobj.write(sb.toString());
                outobj.close();

            }catch (Exception e){
              System.err.println("Error: " + e.getMessage());
            }
            
            msg = Toast.makeText(AddActivity.this,
                    "Hotovo", Toast.LENGTH_LONG);
                 msg.show();
                 Lahvodroid.parseXML();
                 finish();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {

                String contents = intent.getStringExtra("SCAN_RESULT");

                Toast andEggs = Toast.makeText(AddActivity.this, contents, Toast.LENGTH_SHORT);
    			andEggs.show();
                
                textEditBarcode = (EditText)findViewById(R.id.widget153);
                textEditBarcode.setText(contents, EditText.BufferType.EDITABLE);        
                

                // Handle successful scan
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
    }
       
}
